import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    products: [
      { id: 1, name: '手机', price: 1000, quantity: 0 },
      { id: 2, name: '电脑', price: 2000, quantity: 0 },
      { id: 3, name: '键盘', price: 200, quantity: 0 }
    ]
  },
  getters: {
    products: state => state.products,
    cartTotal: state => {
      return state.products.reduce((total, product) => {
        return total + (product.price * product.quantity)
      }, 0)
    },
    cartItemCount: state => {
      return state.products.reduce((count, product) => count + product.quantity, 0)
    }
  },
  mutations: {
    INCREMENT_QUANTITY(state, productId) {
      const product = state.products.find(p => p.id === productId)
      if (product) product.quantity++
    },
    DECREMENT_QUANTITY(state, productId) {
      const product = state.products.find(p => p.id === productId)
      if (product && product.quantity > 0) product.quantity--
    }
  },
  actions: {
    incrementQuantity({ commit }, productId) {
      commit('INCREMENT_QUANTITY', productId)
    },
    decrementQuantity({ commit }, productId) {
      commit('DECREMENT_QUANTITY', productId)
    }
  }
})